package com.example.myapplication.ui.dashboard;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.myapplication.Adapter.ContactAdapter;
import com.example.myapplication.Bean.User;
import com.example.myapplication.ChatAcvicity;
import com.example.myapplication.R;

import org.litepal.LitePal;

import java.util.List;

/* 适配器   子项布局   数据源  */
public class DashboardFragment extends Fragment {
    private ListView contactlv;
    ContactAdapter adapter;
    List<User> userList;//全局变量

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard,
                container, false);
        initView(view);
        setListener();
        return view;
    }

    private void setListener() {
        /*联系人*/
        contactlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                获取名字
                SharedPreferences sp = getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                User user = userList.get(position);
                editor.putInt("friend", user.getId());
                editor.putString("friendname", user.getName());
                editor.putInt("friendimg", user.getUserimg());
                editor.apply();
                Intent it = new Intent(getContext(), ChatAcvicity.class);
                startActivity(it);
            }
        });


    }


    private void initView(View view) {
        userList = LitePal.findAll(User.class);
        contactlv = view.findViewById(R.id.contactlv);
        adapter = new ContactAdapter(getContext(), R.layout.contact_item, userList);
        /*因为是碎片写法，所以用的是getContext ,*/
        contactlv.setAdapter(adapter);

    }

}